package com.taotao.sso.service.impl;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.zookeeper.Op.Create;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import com.taotao.common.pojo.TaotaoResult;
import com.taotao.mapper.TbUserMapper;
import com.taotao.pojo.TbUser;
import com.taotao.pojo.TbUserExample;
import com.taotao.pojo.TbUserExample.Criteria;
import com.taotao.sso.service.UserRegisterService;
@Service
public class UserRegisterServiceImpl implements UserRegisterService{
	//注入dao
	@Autowired
	private TbUserMapper userMapper;
	@Override
	public TaotaoResult checkUserInfo(String param, Integer type) {
		TbUserExample example = new TbUserExample();
		Criteria criteria = example.createCriteria();
		if (type == 1) {
			criteria.andUsernameEqualTo(param);
		}else if (type == 2) {
			criteria.andPhoneEqualTo(param);
		}else if (type == 3) {
			criteria.andEmailEqualTo(param);
		}else {
			return TaotaoResult.build(400, "非法的参数");
		}
		List<TbUser> list = userMapper.selectByExample(example);
		if (list == null || list.size() == 0) {
			//如果没有返回true
			return TaotaoResult.ok(true);
		}
		return TaotaoResult.ok(false);
	}
	@Override
	public TaotaoResult registUser(TbUser user) {
		if (StringUtils.isBlank(user.getUsername()) || StringUtils.isBlank(user.getPassword())) {
			return TaotaoResult.build(400, "用户名和密码不能为空");
		}
		TaotaoResult result = checkUserInfo(user.getUsername(), 1);
		if (!(boolean) result.getData()) {
			return TaotaoResult.build(400, "用户名不能重复");
		}
		if (StringUtils.isNoneBlank(user.getPhone())) {
			result = checkUserInfo(user.getPhone(), 2);
			if (!(boolean) result.getData()) {
				return TaotaoResult.build(400, "手机号已被使用");
			}
		}
		if(StringUtils.isNoneBlank(user.getEmail())){
			result = checkUserInfo(user.getEmail(), 3);
			if (!(boolean) result.getData()) {
				return TaotaoResult.build(400, "邮箱已被占用");
			}
		}
		//密码进行加密
		String md5PassWord = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
		//补全user属性
		user.setCreated(new Date());
		user.setUpdated(new Date());
		user.setPassword(md5PassWord);
		//向数据库中插入数据
		userMapper.insert(user);
		return TaotaoResult.ok();
	}

}
